package com.lw.leetcode.sort.b;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * 1801. 积压订单中的订单总数
 *
 * @author liw
 * @version 1.0
 * @date 2023/1/2 10:09
 */
public class GetNumberOfBacklogOrders {

    public static void main(String[] args) {
        GetNumberOfBacklogOrders test = new GetNumberOfBacklogOrders();

        // 34
        int[][] arr =  {{26,7,0},{16,1,1},{14,20,0},{23,15,1},{24,26,0},{19,4,1},{1,1,0}};

        int numberOfBacklogOrders = test.getNumberOfBacklogOrders(arr);
        System.out.println(numberOfBacklogOrders);
    }

    public int getNumberOfBacklogOrders(int[][] orders) {
        PriorityQueue<Long> as = new PriorityQueue<>((a, b) -> Long.compare(b, a));
        PriorityQueue<Long> bs = new PriorityQueue<>();
        for (int[] order : orders) {
            int p = order[0];
            int c = order[1];
            if (order[2] == 0) {
                while (!bs.isEmpty() && c != 0) {
                    Long peek = bs.peek();
                    int p1 = (int) (peek >> 32);
                    if (p1 > p) {
                        break;
                    }
                    int c1 = peek.intValue();
                    bs.poll();
                    if (c >= c1) {
                        c -= c1;
                    } else {
                        bs.add(peek - c);
                        c = 0;
                    }
                }
                if (c != 0) {
                    as.add(((long)p << 32) + c);
                }
            } else {
                while (!as.isEmpty() && c != 0) {
                    Long peek = as.peek();
                    int p1 = (int) (peek >> 32);
                    if (p1 < p) {
                        break;
                    }
                    int c1 = peek.intValue();
                    as.poll();
                    if (c >= c1) {
                        c -= c1;
                    } else {
                        as.add(peek - c);
                        c = 0;
                    }
                }
                if (c != 0) {
                    bs.add(((long)p << 32) + c);
                }
            }
        }
        long v = 0;
        while (!as.isEmpty()) {
            v = (v + ( as.poll().intValue())) % 1000000007;
        }
        while (!bs.isEmpty()) {
            v = (v + (bs.poll().intValue())) % 1000000007;
        }
        return (int) v;
    }

}
